<template>
   
    <view class="page-container" :style="{ paddingTop: vuex_custom_bar_height + 'px' }"> 
        <tn-nav-bar fixed backgroundColor="tn-main-gradient-orangeyellow">
            儿保 
            <template slot="right">
                <view class="tn-flex tn-flex-row-center tn-margin-right" @click="addOpen">
                    <text class="tn-text-md tn-color-white">添加测量</text>
                </view>
            </template>
        </tn-nav-bar>

        <view class="child-care">
            <view class="header">
                <van-nav-bar title="宝宝呵护" left-arrow @click-left="$router.back()" />
            </view>
            <view class="content">
                <view class="calendar-container">
                    <view class="tn-flex tn-flex-row-center tn-margin-bottom-sm">
                        <van-icon name="clock-o" size="18px" style="margin-right: 5px; color: #1989fa;" />
                        <text class="tn-text-lg tn-icon-clock" style="margin: 0; color: #333; font-weight: 500;">预约提醒</text>
                    </view>
                    <custom-calendar ref="customCalendar" :initial-marked-dates="markedDates"
                        @update-marked-dates="handleMarkDate"></custom-calendar>
                </view>
                <view class="list-container">
                    <van-list
                        v-model="loading"
                        :finished="finished"
                        finished-text="没有更多了"
                    >
                        <van-cell
                            v-for="item in list"
                            :key="item.id"
                            :title="item.title"
                            :label="item.time"
                            @click="showPopup(item)"
                        ></van-cell>
                    </van-list>
                </view>

                <!-- 测量记录列表 -->
                <view class="section-title">
                    <text class="tn-text-lg" style="font-weight: 500;">测量记录</text>
                    <text class="view-more" @click="viewMore">查看更多</text>
                </view>
                <view class="records-list">
                    <template v-if="measurementRecords.length > 0">
                        <view v-for="record in measurementRecords" 
                              :key="record.id" 
                              class="record-item" 
                              @click="editRecord(record)">
                            <view class="record-header">
                                <text class="record-time">{{ record.recordedAt }}</text>
                                <text class="record-edit">编辑</text>
                            </view>
                            <view class="record-content">
                                <view class="record-data">
                                    <text class="data-label">身高</text>
                                    <text class="data-value">{{ record.height }}<text style="font-size: 12px;">cm</text></text>
                                </view>
                                <view class="record-data">
                                    <text class="data-label">体重</text>
                                    <text class="data-value">{{ record.weight }}<text style="font-size: 12px;">kg</text></text>
                                </view>
                                <view class="record-data">
                                    <text class="data-label">头围</text>
                                    <text class="data-value">{{ record.headCircumference }}<text style="font-size: 12px;">cm</text></text>
                                </view>
                            </view>
                            <view v-if="record.doctorAdvice" class="record-advice">
                                <text class="advice-label">医生建议</text>
                                <text class="advice-content">{{ record.doctorAdvice }}</text>
                            </view>
                        </view>
                    </template>
                    <view v-else class="no-records">
                        <text class="tn-icon-info no-records-icon"></text>
                        <view>暂无测量记录</view>
                    </view>
                </view>
            </view>
            <van-overlay :show="showOverlay">
                <view class="wrapper">
                    <van-loading type="spinner" color="#1989fa" />
                </view>
            </van-overlay>
        </view>
    </view>
</template>

<script>
import CustomCalendar from '@/components/custom-calendar.vue';
import { plan, planDelete,planSet } from "@/api/plan.js";
import { childGet, childSet } from "@/api/child.js";
import { mapState } from 'vuex';
export default {
    components: {
        CustomCalendar,
    },
    data() {
        return {
            type: 2,
            markedDates: [],
            planMap: new Map(), // 存储日期和plan ID的映射
            loading: false,
            finished: false,
            show: false,
            showOverlay: false,
            popupData: {},
            list: [],
            currentDate: '',
            minDate: '',
            maxDate: '',
            measurementRecords: [],
        };
    },
    computed: {
        ...mapState(['userInfo']),
    },
    methods: {
        /**
         * @description:  处理日历标记日期
         * @param {string} dateStr 日期字符串
         * @return {*}
         */
        async handleMarkDate(dateStr) {
            if (!dateStr) return;
            try {
                const response = this.planMap.has(dateStr)
                    ? await planDelete({
                        id: this.planMap.get(dateStr)
                    })
                    : await planSet({
                        id:0,
                        type: this.type,
                        planDate: dateStr,
                        planName: '儿保提醒',
                        isRemind: true,
                        selectedContacts: this.userInfo.familys?.map(family => (family.id)) || []
                    });
                this.getData();
                return response;

            } catch (error) {
                console.error('Error marking date:', error);
                throw error; 
            }
        },
        async getData() {
            try {
                const res = await plan({ type: this.type });
                if (!res || !res.length) {
                    this.markedDates = [];
                    this.planMap.clear();
                    return;
                }
                this.markedDates = res.map(item => item.createdAt?.split(' ')[0]).filter(Boolean);
                this.planMap.clear();
                res.forEach(item => {
                    const date = item.createdAt?.split(' ')[0];
                    if (date) {
                        this.planMap.set(date, item.id);
                    }
                });
            } catch (error) {
                console.error('Error updating list data:', error);
            }
        },
        addOpen() {
            uni.navigateTo({
                url: '/pages/child/childCareAdd'
            });
        },
        showPopup(item) {
            this.popupData = item;
            this.show = true;
        },
        async getMeasurementRecords() {
            try {
                const response = await childGet(); 
                if (response && Array.isArray(response)) {
                    this.measurementRecords = response.slice(0, 1);
                }
            } catch (error) {
                console.error('Error getting measurement records:', error);
            }
        },
        editRecord(record) {
            uni.navigateTo({
                url: `/pages/child/childCareAdd?id=${record.id}`
            });
        },
        viewMore() {
            uni.navigateTo({
                url: '/pages/growth_record/growth_record'
            });
        },
    },
    onShow() {
        this.getData();
        this.getMeasurementRecords();
    }
};
</script>

<style>
.section-title {
    margin: 20px;
    padding-left: 12px;
    border-left: 4px solid #ffa500;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.section-title::before {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    background: #ffa500;
    border-radius: 50%;
    margin-right: 8px;
}

.view-more {
    color: #ffa500;
    font-size: 14px;
    padding: 4px 12px;
    border: 1px solid #ffa500;
    border-radius: 15px;
    margin-right: 10px;
}

.record-item {
    background: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid #f0f0f0;
    transition: all 0.3s ease;
}

.record-item:active {
    transform: scale(0.98);
    background: #fafafa;
}

.record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #eee;
}

.record-time {
    color: #666;
    font-size: 14px;
    background: #f8f8f8;
    padding: 4px 8px;
    border-radius: 4px;
}

.record-edit {
    color: #ffa500;
    font-size: 14px;
    padding: 4px 12px;
    border: 1px solid #ffa500;
    border-radius: 15px;
    transition: all 0.3s ease;
}

.record-edit:active {
    background: #fff5e6;
}

.record-content {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 15px;
}

.record-data {
    background: #f8f8f8;
    padding: 10px;
    border-radius: 8px;
    text-align: center;
}

.data-label {
    color: #999;
    font-size: 12px;
    margin-bottom: 4px;
    display: block;
}

.data-value {
    color: #333;
    font-size: 16px;
    font-weight: 600;
    display: block;
}

.record-advice {
    background: #fff5e6;
    border-radius: 8px;
    padding: 12px;
    margin-top: 12px;
}

.advice-label {
    display: block;
    color: #ffa500;
    font-size: 14px;
    margin-bottom: 8px;
    font-weight: 500;
}

.advice-content {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
    white-space: pre-wrap;
    word-break: break-all;
}

/* 添加无数据时的样式 */
.no-records {
    text-align: center;
    padding: 30px 0;
    color: #999;
}

.no-records-icon {
    font-size: 48px;
    margin-bottom: 10px;
    color: #ddd;
}

/* 添加加载动画 */
.record-item-enter-active,
.record-item-leave-active {
    transition: all 0.3s ease;
}

.record-item-enter-from,
.record-item-leave-to {
    opacity: 0;
    transform: translateY(20px);
}
</style>